﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using LibraryMusicStore;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.DXErrorProvider;
using MvcMusicStore;
using System.IO;

namespace AppMusicStore
{
    public partial class frmAlbumEditor : DevExpress.XtraEditors.XtraForm
    {
        IRepository<Album> albumRepository;
        IRepository<Artist> artistRepository;
        IRepository<Genre> genreRepository;
        string strNewImagePath;
        internal int? id;

        internal IRepository<Album> AlbumRepository 
        {
            get { return albumRepository; }
            set { albumRepository = value; }
        }

        public frmAlbumEditor()
        {
            InitializeComponent();
        }

        private void frmAlbumEditor_Load(object sender, EventArgs e)
        {
            //if (!Common.TestConnection(db))
            //{
            //    this.Close();
            //    return;
            //}
            try
            {
                //albumRepository = new Repository<Album>();
                artistRepository = new Repository<Artist>(albumRepository.GetContext());
                genreRepository = new Repository<Genre>(albumRepository.GetContext());

                RetriveData();
                if (id != null)
                    InitAlbum();
                else
                    this.layoutId.HideToCustomization();

                btnCancel.CausesValidation = false;
            }
            catch (Exception)
            {
                this.Close();
                throw;
            }
        }

        private void RetriveData()
        {
            try
            {
                bindingSourceArtist.DataSource = artistRepository.GetAll()
                    .OrderByDescending(a => a.ArtistId);
                bindingSourceGenre.DataSource = genreRepository.GetAll()
                    .OrderByDescending(g => g.GenreId);
                lupArtist.ItemIndex = 0;
                lupGenre.ItemIndex = 0;
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void InitAlbum()
        {
            try
            {
                lblId.Text = "Số album: " + id;

                var album = albumRepository.GetById((int)id);
                //db.Albums.Single(a => a.AlbumId == id);

                txtTitle.Text = album.Title;
                calcPrice.Text = album.Price.ToString();
                bteAlbumUrl.EditValue = album.AlbumArtUrl;
                lupArtist.EditValue = album.ArtistId;
                lupGenre.EditValue = album.GenreId;
                
                var absoluteUri = new Uri(new Uri(Application.StartupPath), "../../MvcMusicStore");

                if (File.Exists(absoluteUri.LocalPath + album.AlbumArtUrl))
                {
                    pictureEdit1.Properties.SizeMode = PictureSizeMode.Stretch;
                    pictureEdit1.Image = Image.FromFile(absoluteUri.LocalPath + album.AlbumArtUrl);
                    
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        #region "Button click"
        private void btnAccept_Click(object sender, EventArgs e)
        {
            //validate control
            this.ValidateChildren();

            if (ErrorProvider1.HasErrors)
            {
                foreach (var item in ErrorProvider1.GetControlsWithError())
                {
                    item.Focus();
                    Common.ShowErrorBox(ErrorProvider1.GetError(item));
                    return;
                }
            }

            //switch
            if (id != null)
                Edit();
            else
                Insert();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                if (id != null)
                {
                    var album = albumRepository.GetById((int)id);
                        //Common.GetAlbumById(id, db);
                    if (CheckDiff(album))
                    {
                        DialogResult rs = Common.ShowQuestionBox("Lưu thay đổi ? ", "yesnocancel");
                        if (rs == DialogResult.Yes)
                            btnAccept.PerformClick();
                        else if (rs == DialogResult.Cancel)
                            return;
                    }
                }
            }
            catch (Exception)
            {
                this.Close();
                throw;
                //Common.ShowErrorBox(ex.Message);
            }
            this.Close();
        }
        #endregion

        #region Insert, Edit ...
        private void Edit()
        {
            try
            {
                var album = albumRepository.GetById((int)id);
                    //Common.GetAlbumById(id, db);
                if (!CheckDiff(album))
                {
                    this.Close();
                    return;
                }
                if (album.Title != txtTitle.Text.Trim())
                {
                    //duplicate name
                    if (albumRepository.Duplicate(a => a.Title.ToUpper()
                                .Contains(txtTitle.Text.ToUpper().Trim())))
                    {
                        Common.ShowErrorBox("Tựa đề đã có");
                        txtTitle.Focus();
                        return;
                    }
                }

                DialogResult result = Common.ShowQuestionBox("Sửa album " + id + " ?", "okcancel");

                if (result == DialogResult.OK)
                {
                    InitNewAlbum(album);
                    albumRepository.SubmitChanges();
                    //db.SubmitChanges();

                    Common.ShowInfomationBox("Sửa thành công album " + id);

                    this.DialogResult = DialogResult.OK;
                }

            }
            catch (Exception )
            {
                //Common.ShowErrorBox(ex.Message);
                this.Close();
                throw;
            }
        }

        private bool CheckDiff(Album album)
        {
            if (album.Title != txtTitle.Text.Trim()
                || album.Price != Convert.ToDecimal(calcPrice.Text)
                || album.AlbumArtUrl != bteAlbumUrl.EditValue.ToString()
                || album.ArtistId != Convert.ToInt32(lupArtist.EditValue)
                || album.GenreId != Convert.ToInt32(lupGenre.EditValue))
            {
                return true;
            }

            return false;
        }

        private void InitNewAlbum(Album album)
        {
            try
            {
                album.Title = txtTitle.Text.Trim();
                album.Price = Convert.ToDecimal(calcPrice.Text);
                if (strNewImagePath != null)
                {
                    // "/content/images/name.xxx"
                    var str = "/content/images/" + new FileInfo(strNewImagePath).Name;
                    album.AlbumArtUrl = str;
                }
                else album.AlbumArtUrl = bteAlbumUrl.Text;
                
                if (lupGenre.EditValue != null)
                    album.Genre = genreRepository.GetById(Convert.ToInt32(lupGenre.EditValue));
                if (lupArtist.EditValue != null)
                    album.Artist = artistRepository.GetById(Convert.ToInt32(lupArtist.EditValue));
                album.Deleted = false;
                //album.Artist = db.Artists.Single(a => a.ArtistId == Convert.ToInt32(lupArtist.EditValue));
                //album.Genre = db.Genres.Single(g => g.GenreId == Convert.ToInt32(lupGenre.EditValue));
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void Insert()
        {
            try
            {
                var album = new Album();
                //duplicate name
                if (albumRepository.Duplicate(a => a.Title.ToUpper()
                            == txtTitle.Text.ToUpper().Trim()
                            && a.Deleted != true))
                {
                    Common.ShowErrorBox("Tựa đề đã có");
                    txtTitle.Focus();
                    return;
                }
                else if (albumRepository.Duplicate(a => a.Title.ToUpper()
                            == txtTitle.Text.ToUpper().Trim()
                            && a.Deleted == true))
                {
                    album = albumRepository.Where(a => a.Title.ToUpper() == 
                        txtTitle.Text.ToUpper().Trim()).SingleOrDefault();

                    album.Deleted = false;
                    InitNewAlbum(album);
                    albumRepository.SubmitChanges();
                    id = album.AlbumId;
                }
                else
                {
                    //create new album object
                    InitNewAlbum(album);

                    //insert into database
                    albumRepository.InsertOnSubmit(album);
                    albumRepository.SubmitChanges();
                    //db.Albums.InsertOnSubmit(album);
                    //db.SubmitChanges();
                }
                
                Common.ShowInfomationBox("Thêm thành công album " + album.Title);

                this.DialogResult = DialogResult.OK;
            }
            catch (Exception)
            {
                //Common.ShowErrorBox(ex.Message);
                this.Close();
                throw;
            }
        }
        #endregion

        private void Check(object sender, CancelEventArgs e)
        {
            string str = null;
            
            //title required
            if (sender.GetType().Name == "TextEdit")
            {
                TextEdit txt = (TextEdit)sender;
                if (txt.Text.Trim().Length == 0)
                    str = "Chưa nhập tựa đề";
            }
            else if (sender.GetType().Name == "CalcEdit")
            {
                decimal d1 = 1, d2 = 100;
                CalcEdit calc = (CalcEdit)sender;
                if (calc.Text.Trim().Length == 0)
                    str = "Chưa nhập giá";
                else if (Convert.ToDecimal(calc.EditValue) < 1 || Convert.ToDecimal(calc.EditValue) > 100)
                    str = d1.ToString() + "-" + d2.ToString();
            }
            else if (sender.GetType().Name == "ButtonEdit")
            {
                Control txt = (Control)sender;
                if (txt.Text.Trim().Length == 0)
                    str = "Chưa chọn hình";
            }

            ErrorProvider1.SetIconAlignment((Control)sender, ErrorIconAlignment.MiddleRight);
            ErrorProvider1.SetError((Control)sender, str);
        }
        
        private void bteAlbumUrl_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            try
            {
                OpenFileDialog fileDialog = new OpenFileDialog();
                //fileDialog.Filter = "Image Files (JPEG,GIF,BMP,PNG,ICO)|*.jpg;*.jpeg;*.gif;*.bmp;*.png;*ico";
                fileDialog.Filter = "All Image Files ( JPEG,GIF,BMP,PNG,ICO )|*.jpg;*.jpeg;*.gif;*.bmp;*.png;*ico|JPEG Files ( *.jpg;*.jpeg )|*.jpg;*.jpeg|GIF Files ( *.gif )|*.gif|BMP Files ( *.bmp )|*.bmp|PNG Files ( *.png )|*.png|Icon Files ( *.ico )|*.ico";
                if (fileDialog.ShowDialog() == DialogResult.OK)
                {
                    //string myPath = System.Reflection.Assembly.GetEntryAssembly().Location;
                    //string myDir = System.IO.Path.GetDirectoryName(myPath);
                    //string path = System.IO.Path.Combine(myDir, "project2.exe");
                    //var p = Application.LocalUserAppDataPath;

                    var absoluteUri = new Uri(new Uri(Application.StartupPath), "../../MvcMusicStore/content/images/");
                    strNewImagePath = absoluteUri.LocalPath + new FileInfo(fileDialog.FileName).Name;

                    File.Copy(fileDialog.FileName, strNewImagePath, true );

                    bteAlbumUrl.Text = fileDialog.FileName;

                    pictureEdit1.Properties.SizeMode = PictureSizeMode.Stretch;
                    pictureEdit1.Image = Image.FromFile(strNewImagePath);
                }
            }
            catch (Exception)
            {

                throw;
            }
            
        }
    }
}